<template>
  <el-form ref="form" :model="form" :rules="rules" label-width="100px">
    <el-form-item label="标题" prop="title">
      <el-input v-model="form.title" />
    </el-form-item>
    <el-form-item label="是否屏蔽" prop="status">
      <el-switch v-model="form.status" />
    </el-form-item>
    <el-form-item label="内容" prop="content">
      <el-input v-model="form.content" type="textarea" maxlength="400" show-word-limit :autosize="{ minRows: 3, maxRows: 5}" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm('form')">保存</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { adminListNews, insertNews } from '@/api/news'
import { getUserId } from '@/utils/auth'

export default {
  name: 'AddOrUpdateNews',
  props: {
    newsId: {
      type: Number,
      default: -1
    }
  },
  data() {
    return {
      form: {
        title: '',
        status: false,
        content: ''
      },
      rules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        content: [{ required: true, message: '请输入内容', trigger: 'blur' }]
      }
    }
  },
  created() {
    if (this.newsId !== -1) {
      adminListNews({ newsId: this.newsId }).then(res => {
        this.form = res.data[0]
        this.form.status = res.data[0].status === 1
      })
    }
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const form = new FormData()
          form.set('newsId', String(this.newsId))
          form.set('userId', getUserId())
          form.set('title', this.form.title)
          form.set('status', String(this.form.status ? 1 : 0))
          form.set('content', this.form.content)
          insertNews(form).then(res => {
            if (res) {
              this.$message({ message: res.message, type: 'success' })
              this.$emit('updateDialog', false)
            }
          })
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
